<template>
  <div class="Login">
    <div>
      <el-row class="LoginRow" style="width: 100vw">
        <el-col :span="6" offset="9">
          <div class="LoginMain">
            <div class="login-form-container">
              <div class="logo-container">
                <img src="@/assets/logo.png" class="logo" />
                <h2 class="platform-name">IT培优综合服务平台</h2>
              </div>

              <el-form
                  :model="form"
                  :rules="rules"
                  ref="loginForm"
                  label-position="top"
                  class="login-form"
              >
                <el-form-item
                    prop="userName"
                >
                  <el-input
                      class="input-field"
                      placeholder="请输入账号"
                      v-model="form.userName"
                  ></el-input>
                </el-form-item>
                <el-form-item
                    prop="password"
                >
                  <el-input
                      class="input-field"
                      type="password"
                      placeholder="请输入密码"
                      v-model="form.password"
                  ></el-input>
                </el-form-item>
              </el-form>

              <el-button
                  class="login-btn"
                  @click="handleLogin"
                  type="primary"
                  :loading="loading" >
                登 录
              </el-button>

              <div class="register-container">
                <div class="register-text" @click="register">
                  注册账号
                </div>
              </div>
              <div class="forgot-password">
                <el-link
                    class="forgot-link"
                    @click="forgetPassword"
                >
                  忘记密码
                </el-link>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import CryptoJS from "crypto-js";
import { debounce } from "lodash";
import { setRoutes } from "@/router";

export default {
  data() {
    return {
      form: {
        userName: "",
        password: ""
      },
      rules: {
        userName: [
          { required: true, message: "请输入账号", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" }
        ]
      },
      loading: false, // 用于控制按钮加载状态
      debouncedLogin: null,
      errorMessage: "", // 用于防止重复提示错误信息
    };
  },
  mounted() {
    // 防抖函数，延迟1秒发起请求（原有逻辑）
    this.debouncedLogin = debounce(this.login, 1000);
  },
  beforeDestroy() {
    if (this.debouncedLogin) {
      this.debouncedLogin.cancel(); // 组件销毁前取消防抖函数（原有逻辑）
    }
  },
  methods: {
    register() {
      this.$router.push({ name: "register" });
    },
    forgetPassword() {
      this.$router.push({ name: "forgetPassword" });
    },

    handleLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.errorMessage = ""; // 清除之前的错误提示（原有逻辑）
          this.loading = true; // 显示按钮加载状态（原有逻辑）
          this.debouncedLogin(); // 调用防抖后的登录方法（原有逻辑）
        } else {
          // 如果表单验证失败，设置错误信息（原有逻辑）
          this.errorMessage = "请完善登录信息";
          this.messageError(this.errorMessage);
        }
      });
    },
    htmlEscape(str) {
      return str.replace(/[&<>"'\/]/g, function (s) {
        switch (s) {
          case '&':
            return '&amp;';
          case '<':
            return '&lt;';
          case '>':
            return '&gt;';
          case '"':
            return '&quot;';
          case '"':
            return '&#39;';
          case '/':
            return '&#x2F;';
        }
      });
    },
    login() {
      // 确保在发送请求前对密码进行加密
      const hashedPassword = CryptoJS.MD5(this.form.password).toString(CryptoJS.enc.Hex);
      this.form.password = hashedPassword;

      // 对用户名进行HTML转义，防止xss攻击
      this.form.userName = this.htmlEscape(this.form.userName);

      // 发起登录请求
      this.request.post("/web/login", this.form)
          .then((res) => {
            this.loading = false; // 请求完成后取消加载状态（原有逻辑）

            if (res.code === "200") {
              localStorage.setItem("user", JSON.stringify(res.data));
              this.messageSuccess("登录成功");
              setRoutes();

              // 根据角色跳转（原有逻辑）
              setTimeout(() => {
                if (
                    res.data.role.includes("ROLE_TEACHER") ||
                    res.data.role.includes("ROLE_ADMIN")
                ) {
                  this.$router.push({name: "backHome"});
                } else if (res.data.role.includes("ROLE_USER")) {
                  this.$router.push({name: "frontHome"});
                }
              }, 1000);
            } else {
              // 如果登录失败，显示错误信息
              this.messageError("用户名或密码错误");
            }
          })
          .catch((error) => {
            this.loading = false; // 请求失败后取消加载状态
            console.error("登录请求失败：", error);
            this.messageError("登录失败，请稍后再试");
          });
    },
    messageSuccess(message) {
      this.$message({type: "success", message});
    },
    messageError(message) {
      // 防止多次提示相同的错误信息（原有逻辑）
      if (this.errorMessage!== message) {
        this.$message({type: "error", message});
        this.errorMessage = message; // 保存错误信息，避免重复提示
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.Login {
  background: url("@/assets/登录背景.jpeg") no-repeat center center fixed;
  height: 100vh;
  background-size: cover;
  display: flex;
  align-items: center;
  justify-content: center;
}

.LoginRow {
  width: 100%;
  display: flex;
  justify-content: center;
}

.LoginMain {
  background-color: rgba(255, 255, 255, 0.85); /* 增加透明度 */
  padding: 40px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1); /* 更柔和的阴影效果 */
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  max-width: 450px;
}

.login-form-container {
  width: 100%;
  text-align: center;
}

.logo-container {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 30px;
}

.logo {
  height: 45px;
  width: 45px;
}

.platform-name {
  color: #333;
  font-size: 20px;
  margin-left: 15px;
  font-weight: 500;
}

.input-field {
  width: 85%;
  margin-bottom: 18px;
  border-radius: 8px;
  padding: 12px;
  background-color: #f7f7f7; /* 更简洁的背景色 */
  border: 1px solid #ddd; /* 统一的边框颜色 */
  font-size: 16px;
}

.input-field:focus {
  border-color: #42b983; /* 聚焦时的颜色 */
}

.login-btn {
  width: 85%;
  background-color: #42b983;
  border-radius: 8px;
  padding: 14px;
  font-size: 16px;
  color: white;
  border: none;
}

.login-btn:hover {
  background-color: #36a67c;
}

.forgot-password {
  margin-top: 15px;
}

.forgot-link {
  color: #42b983;
  font-size: 14px;
  text-decoration: none;
}

.forgot-link:hover {
  text-decoration: underline;
}

/* 注册按钮文字样式 */
.register-container {
  width: 100%;
  text-align: center;
  margin-top: 20px;
}

.register-tooltip {
  position: relative;
}

.register-text {
  cursor: pointer;
  font-size: 16px;
  color: #42b983;
  font-weight: 600;
}

.register-text:hover {
  text-decoration: underline;
}
</style>
